﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Cryptography;


namespace Talk
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] != null)
            {
                Response.Redirect("/index.aspx");
            }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            try
            {
                errormsg.Text = "";
                Regex r = new Regex("[^a-zA-Z0-9]");
                if (username.Text.Length > 12 || username.Text.Length<3 || r.IsMatch(username.Text))
                {
                    errormsg.Text = "用户名错误！";
                    return;
                }
                SHA1 sha1 = SHA1.Create();
                byte[] shares = sha1.ComputeHash(System.Text.Encoding.Default.GetBytes(password.Text));
                string passsha1 = BitConverter.ToString(shares, 7, 7);
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["talkconn"].ConnectionString);
                conn.Open();
                string sql = "select * from Users where Username = '"
                    + username.Text + "'";
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader data = cmd.ExecuteReader();
                if(!data.HasRows)
                {
                    errormsg.Text = "用户不存在！";
                    conn.Close();
                    return;
                }
                data.Read();
                if(data["Password"].ToString()!=passsha1)
                {
                    errormsg.Text = "密码错误！";
                    conn.Close();
                    return;
                }
                Session["UserID"] = data["UserID"];
                Session["Username"] = data["Username"];
                Session["nMessage"] = data["nMessage"];
                Session["nFollower"] = data["nFollower"];
                Session["nFollowing"] = data["nFollowing"];
                data.Close();
                cmd.CommandText = "insert into Actions(UserID,What,Time,IP) values("
                      + Session["UserID"].ToString()
                      + ",'" + Session["Username"] + "登入','"
                      + DateTime.Now.ToString() + "','"
                      + Request.UserHostAddress.ToString()
                      + "');"; 
                cmd.ExecuteNonQuery();			
                conn.Close();
                Response.Redirect("/index.aspx");
            }
            catch (System.Exception ex)
            {
                errormsg.Text = ex.Message;
            }
        }
    }
}
